import { App, Button, Card, Col, Form, Input, message, Row, Table } from 'antd';
import '../candidate/index.scss';
import { queryCandidate,deleteCandidate } from '@/apis/candidate'
import { useEffect, useRef, useState } from 'react';
import type { Candidate, CandidateDto } from '@/types';
import { AuditOutlined, DeleteOutlined, FormOutlined, PlusOutlined, SearchOutlined } from '@ant-design/icons';
import CandidateAddForm from '@/components/CandidateForm';
import ArrangeInterviewForm from '@/components/ArrangeInterviewForm';

const Candidate = () => {
    const { modal } = App.useApp();
    /** 
     * 更改查询条件回调 
     * 调用时机
     * 1.修改当前页数和每页显示条数时
     * 2.查询条件表单的条件修改
     */
    const changeSeleteCondition = (params: CandidateDto) => {
        console.log("changeSeleteCondition========>",params);
        setQueryForm(params);   
    }

    /** 查询  */
    const getCandidateData = async () => {
        setLoading(true);
        const res = await queryCandidate(queryForm);
        console.log("候选人数据=======>",res.data.records);
        // 获取数据为空 且 当前页数不为1时，将当前页数-1再查一遍
        /**
         * 解决：
         *  1.在删除第二页最后一条数据后，重新查询时当前页数还是2，解决后：查不到之后，会-1变成1
         *  2.当前在第二页，然后搜索存在的数据的条件，若存在的数据不满足2页，则会显示为空 解决后：查不到之后，会-1变成1
         */
        if (res.data.records.length === 0 && queryForm.current !== 1) {
            setQueryForm({
                ...queryForm,
                current: queryForm.current - 1
            })
            return;
        }
        setTableData(res.data.records);
        setTotal(res.data.total);
        setLoading(false);
    }

    /** 新增 */
    const addCandidateData = async () => {
        candidateFormRef.current.open();
    }

    /** 编辑  */
    const editCandidateData = async (record: Candidate) => {
        candidateFormRef.current.open(record);
    }

    /** 删除 */
    const removeCandidate = async (id: string) => {
        const deleteIds: string[] = [];
        deleteIds.push(id);
        modal.confirm({
            title: '温馨提示',
            content: '是否删除选中的数据？',
            okText: '确认',
            cancelText: '取消',
            async onOk(){
               const res = await deleteCandidate(deleteIds);
                if (res.code === 200) {
                    message.success("删除成功！");
                    await getCandidateData();
                }else {
                    message.success(res.msg);
                } 
            },
            onCancel: () => {

            }
        })
    }

    /** 批量删除  */
    const removeCandidateBatch = async () => {
        if (selectDataIds.current.length === 0) {
            message.warning('请先选择数据再进行操作！')
            return;
        }
        modal.confirm({
            title: '温馨提示',
            content: '是否删除选中的数据？',
            okText: '确认',
            cancelText: '取消',
            async onOk(){
               const res = await deleteCandidate(selectDataIds.current);
                if (res.code === 200) {
                    message.success("删除成功！");
                    await getCandidateData();
                }else {
                    message.error(res.msg);
                } 
            },
            onCancel: () => {

            }
        })
    }

    /** 安排面试 */
    const arrangeInterview = () => {
        if (selectDataIds.current && selectDataIds.current.length === 0) {
            message.warning('请选择候选人之后再安排面试！');
            return;
        }
        arrangeInterviewFormRef.current.open(selectDataIds.current);
    }

    /** 表格选中回调  */
    const tabSelectChange = (selectedRowKeys: React.Key[], selectedRows: Candidate[]) => {
        selectDataIds.current = selectedRowKeys as string[];
        console.log(`selectedRowKeys: ${selectDataIds.current}`, 'selectedRows: ', selectedRows);
    }
    // 查询表单标识
    const [form] = Form.useForm();
    // 表格数据
    const [tableData,setTableData]  = useState<Candidate[]>([]);
    // 总记录数
    const [total,setTotal] = useState(0);
    // 查询条件
    const [queryForm,setQueryForm] = useState<CandidateDto>({
        current: 1,
        size: 6
    })
    // 加载中标识
    const [loading, setLoading] = useState(false);
    // 弹框组件标识
    const candidateFormRef = useRef(null);
    // 安排面试弹窗组件标识
    const arrangeInterviewFormRef = useRef(null);
    // 当前选中的数据行id
    const selectDataIds = useRef<string[]>([]);

    useEffect(() => {
        getCandidateData();
    }, [queryForm]); // 当 queryForm 的值变化时才触发

    const columns = [
        {
            title: '姓名',
            dataIndex: 'name',
        },
        {
            title: '年龄',
            dataIndex: 'age',
        },
        {
            title: '联系号码',
            dataIndex: 'contactNumber',
        },
        {
            title: '生日日期',
            dataIndex: 'birthday',
        },
        {
            title: '操作',
            dataIndex: 'action',
            render: (value: string, record:Candidate) => (
                <>
                    <Row gutter={16}>
                        <Col>
                            <Button onClick={() => editCandidateData(record)} color='primary' variant="outlined" icon={<FormOutlined />}/>
                        </Col>
                        <Col>
                           <Button onClick={() => removeCandidate(record.id!)} color="danger" variant="outlined" icon={<DeleteOutlined />}/>
                        </Col>
                    </Row>
                </>
            ),
        }
    ];

    return (
        <div className='candidate-container'>
            <Card title='查询条件' style={{ borderRadius: 0 }}>
                <Form
                    form={form}
                    layout="inline"
                    name="candidate"
                    labelCol={{ span: 8 }}
                    wrapperCol={{ span: 16 }}
                    style={{ width: '100%' }}
                    initialValues={{ remember: true }}
                    onFinish={(val) => { changeSeleteCondition({...queryForm,...val}) }}
                    autoComplete="off"
                >
                    <Row style={{ width: '100%' }}>
                        <Form.Item<Candidate>
                            label="姓名"
                            name="name"
                        >
                            <Input />
                        </Form.Item>

                        <Form.Item<Candidate>
                            label="联系号码"
                            name="contactNumber"
                        >
                            <Input />
                        </Form.Item>
                    </Row>

                    <Row justify="end" style={{ width: '100%',marginTop: '20px' }}>
                        <Form.Item label={null}>
                            <Button type="primary" onClick={() => arrangeInterview()} htmlType="button" icon={<AuditOutlined />}>
                                安排面试
                            </Button>
                        </Form.Item>
                        <Form.Item label={null}>
                            <Button type="primary" onClick={() => addCandidateData()} htmlType="button" icon={<PlusOutlined />}>
                                新增
                            </Button>
                        </Form.Item>
                        <Form.Item label={null}>
                            <Button variant='solid' color='danger' onClick={() => removeCandidateBatch()} htmlType="button" icon={<DeleteOutlined />}>
                                删除
                            </Button>
                        </Form.Item>
                        <Form.Item label={null}>
                            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                                查询
                            </Button>
                        </Form.Item>
                    </Row>
                </Form>
            </Card>

            <Card title='查询结果' style={{ marginTop: '20px',borderRadius: 0 }}>
                <Table
                    rowKey="id" 
                    loading={loading}
                    pagination={{ 
                        position: ['bottomRight'],
                        current: queryForm.current,
                        pageSize: queryForm.size,
                        total: total,
                        onChange: (current, size) => changeSeleteCondition({...form.getFieldsValue(),current,size}),
                        showTotal: (total) => `共 ${total} 条数据`,
                        showSizeChanger: true,
                        pageSizeOptions: [6,10,20,50,100]
                    }}
                    rowSelection={{ type: 'checkbox',onChange: tabSelectChange }} 
                    dataSource={tableData} 
                    columns={columns} 
                />
            </Card>
            <CandidateAddForm ref={candidateFormRef} reQuery={() => getCandidateData()}></CandidateAddForm>
            <ArrangeInterviewForm ref={arrangeInterviewFormRef} reQuery={() => getCandidateData()}></ArrangeInterviewForm>
        </div>
    )
}

export default Candidate;